$(function() {
  if($.url.decode(getCookie("myTodo")) != "null") {
    document.location.href = "home.jsp";
  }
  $('#userName').example('Username');
  $('#password').example('Password');
  $('#registeredFirstName').example('First name');
  $('#registeredLastName').example('Last name');
  $('#registeredUserName').example('Username');
  $('#registeredEmail').example('E-mail');
  $('#registeredPasswordFake').example('Password');
  $('#registeredPasswordAgainFake').example('Password again');
  $(".actionMessage").delay(3000).slideUp();
  $('#registrationFormContainer').dialog({autoOpen: false, hide: "fadeOut", show: "fadeIn, slow", height: 460, width: 300, modal: true, title: "Registration"});
  $("#registeredFirstName").blur(function() {
    checkLength("#registeredFirstName", "First name", "#msgboxFirstName");
  });

  $("#registeredLastName").blur(function() {
    checkLength("#registeredLastName", "Last name", "#msgboxLastName");
  });

  $("#registeredPassword").blur(function() {
    if ($("#registeredPassword").val().length == 0) {
      changeInputType({current: "registeredPassword", next: "registeredPasswordFake"});
      $("#msgboxPassword").removeClass().html("");
      return;
    }
    if ($("#registeredPasswordAgain").val() != $("#registeredPassword").val()) {
      if ($("#registeredPasswordAgain").val() != "Password again" && $("msgboxPassword").hasClass("messageboxok")) {
        $("#msgboxPassword").removeClass().html("");
        displayAvailability("no", "#msgboxPassword", null, "Does not match second password.");
        return;
      }
    }
    else {
      $("#msgboxPassword").removeClass().html("");
    }
    checkLength("#registeredPassword", "Password", "#msgboxPassword", 5);
  });

  $("#registeredPasswordAgain").blur(function() {
    if ($("#registeredPasswordAgain").val().length == 0) {
      changeInputType({current: "registeredPasswordAgain", next: "registeredPasswordAgainFake"});
      $("#msgboxPasswordAgain").removeClass().html("");
      return;
    }
    if ($("#registeredPasswordAgain").val() != $("#registeredPassword").val() && $("#registeredPasswordAgain").val() != "Password again") {
      $("#msgboxPasswordAgain").removeClass().html("");
      displayAvailability("no", "#msgboxPasswordAgain", null, "Does not match first password.");
      return;
    }
    else {
      $("#msgboxPasswordAgain").removeClass().html("");
    }
    checkLength("#registeredPasswordAgain", "Password again", "#msgboxPasswordAgain", 5);
  });

  $("#registeredUserName").blur(function() {
    var username = $("#registeredUserName").val();
    $("#msgboxUsername").removeClass()
    if (username == "Username") {
      $("#msgboxUsername").html("");
      return;
    }
    if (username.length < 2) {
      $("#msgboxUsername").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
      displayAvailability('no', "#msgboxUsername", null, "Username too short.");
      return;
    }
    $.post("checkUsername", { registeredUserName : username }, function(data) {
      if(data) {
        displayAvailability('yes', "#msgboxUsername", "&#x2713", null);
      return;
    }
    displayAvailability('no', "#msgboxUsername", null, "Username unavailable.");
    }, "json");
});

$("#registeredEmail").blur(function() {
  var email = $("#registeredEmail").val();
  var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  if (email != "E-mail" && !filter.test(email)) {
    $("#msgboxEmail").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
    displayAvailability('no', "#msgboxEmail", null, "Invalid E-mail.");
    return;
  }
  if(email == "E-mail") {
    $("#msgboxEmail").html("");
    return;
  }

  $("#msgboxEmail").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
  $.post("checkEmail", { registeredEmail : email }, function(data) {
    if(data) {
      displayAvailability('yes', "#msgboxEmail", "&#x2713", null);
      return;
    }
    displayAvailability('no', "#msgboxEmail", null, "Email in use");
  }, "json");
});
})
;

function checkLength(field, defaultValue, messageBoxId, minimumSize) {
  if (minimumSize == null) {
    minimumSize = 3;
  }
  if ($(field).val() != defaultValue) {
    $(messageBoxId).removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
    if ($(field).val().length < minimumSize) {
      displayAvailability('no', messageBoxId, null, defaultValue + " too short.");
    }
    else {
      displayAvailability('yes', messageBoxId, "&#x2713", null);
    }
  }
  else {
    $(messageBoxId).removeClass().html('');
  }
}

function checkAllFields() {
  var okSign = $('#okSign').val();
  $('#msgboxRegister').removeClass().html('');
  if ($('#msgboxFirstName').text() != okSign) {
    return showError();
  }
  if ($('#msgboxLastName').text() != okSign) {
    return showError();
  }
  if ($('#msgboxUsername').text() != okSign) {
    return showError();
  }
  if ($('#msgboxEmail').text() != okSign) {
    return showError();
  }
  if ($('#msgboxPassword').text() != okSign) {
    return showError();
  }
  if ($('#msgboxPasswordAgain').text() != okSign) {
    return showError();
  }
  return true;
}

function showError() {
  displayAvailability('no', '#msgboxRegister', null, "Please fill all the fields correctly!");
  return false;
}

function checkAvailability(target) {
  if ($(target.field).val() == target.default)
  {
    $(target.messageSpan).removeClass().html("");
    return;
  }
  $(target.messageSpan).removeClass("messageboxok").removeClass("messageboxerror").addClass('messagebox').text('Checking...').fadeIn("slow");
  var answer;
  $.getJSON("userMock.json",
    function(data) {
      $.each(data.users.user, function(key, value) {
        if (value[target.parameter] == $(target.field).val()) answer = 'no';
      });
      if (answer != 'no') answer = 'yes';
    }).success(function() {
    displayAvailability(answer, target.messageSpan, target.successText, target.errorText)
  });
}

function displayAvailability(data, targetId, successText, failureText) {
  if (data == 'no') {
    $(targetId).fadeTo(200, 0.1, function() {
      $(targetId).html(failureText).addClass('messageboxerror').fadeTo(900, 1);
    });
  }
  if (data == 'yes') {
    $(targetId).fadeTo(200, 0.1, function() {
      $(targetId).html(successText).addClass('messageboxok').fadeTo(900, 1);
    });
  }
}

function saveUser() {
  var result = checkAllFields();
  if (!result) {
    return false;
  }
  var cookieValue = "{\"userName\" : \"" + $('#registeredUserName').val() + "\", \"password\" : \"" + $('#registeredPassword').val() + "\", \"name\" : \"" + $('#registeredFirstName').val() + " " + $('#registeredLastName').val() + "\"}"
  setCookie("myTodo", cookieValue, 2);
  closeRegistrationForm();
  $("#registrationForm").submit();
}

function setCookie(cookieName, cookieValue, daysToLive) {
  var expirationDate = new Date();
  expirationDate.setDate(expirationDate.getDate() + daysToLive);
  var cookieValue = escape(cookieValue) + ((daysToLive == null) ? "" : "; expires = " + expirationDate.toUTCString());
  document.cookie = cookieName + " = " + cookieValue;
  console.log(getCookie("myTodo"));
}

function changeInputType(event) {
  var current = $('#' + event.current + '');
  var next = $('#' + event.next + '');
  if (current.attr('type') == 'password' && current.val().length != 0) {
    return;
  }
  current.addClass('hide');
  next.removeClass('hide');
  if (next.attr('type') != 'text') {
    next.focus();
  } else {
    next.example('Password');
  }
}

function openRegistrationForm() {
  $('#registrationFormContainer').dialog('open');
}

function closeRegistrationForm() {
  $('#registrationFormContainer').dialog('close');
}

function logIn(event) {
  $("#msgboxLogin").removeClass().html('');
  if (event.userName == 'Username' || event.password == "") {
    return showLoginError("Invalid username or password!");
  }

  $.post("checkUserData", { username : event.userName, password : event.password }, function(data) {
    if(data == "false") {
      return showLoginError("Invalid username or password!");
    }
    else {
      deleteCookie("myTodo");
      setCookie("myTodo", "{\"userName\" : \"" + event.userName + "\"}", 1);
      $("#login").submit();
    }
  }, "json");
}

function showLoginError(message) {
  $("#msgboxLogin").addClass("userData");
  displayAvailability('no', '#msgboxLogin', null, message);
  return false;
}

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30653074-1']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script');
  ga.type = 'text/javascript';
  ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(ga, s);
})();